package com.wtwd.campus.send;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.encryptnetty.EncryptChannelMap;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.netty.ChannelMap;
import com.wtwd.campus.service.InjectFeignService;
import com.wtwd.campus.service.WebRemoteService;
import com.wtwd.campus.service.entity.DeviceLog;
import com.wtwd.campus.utils.InjectService;
import com.wtwd.campus.utils.UnicodeUtil;
import io.netty.channel.Channel;
import org.apache.commons.lang.StringUtils;


/**
 * @Author ldaoliang
 * @Date create in 18:06 2021/3/23
 * @Description
 */
public interface Sender {


    Command dealMessage(MqMessage mqMessage);

    default boolean send(Command command) {
        if (command == null) {
            return false;
        }
        DeviceLog deviceLog = new DeviceLog();
        //发送人平台
        deviceLog.setSendUser(Constants.WEB_USER);
        //默认不缓存，判断后缓存修改此值
        deviceLog.setCache(2);
        boolean flag = true;
        String imei = command.getImei();
        int status = command.getStatus();
        /*add in 2021年8月31日11:22:06 by ldaoliang;
       1.增加了加密的传输，与未加密共存，根据redis里存储的加密类型，选择对应的map去搜寻通道
       */
        Integer isEncrypt = InjectService.deviceIsEncrypt(imei);
        if (isEncrypt == null) {
            flag = false;
            command.setLastSendTime(System.currentTimeMillis());
        } else {
            Channel channel = isEncrypt == 1 ? ChannelMap.get(imei) : EncryptChannelMap.get(imei);
            if (channel != null) {
                channel.writeAndFlush(command.getContent());
                command.setStatus(Constants.COMMAND_NOT_RESPONSE);
                command.setLastSendTime(System.currentTimeMillis());
            } else {
                flag = false;
                command.setStatus(Constants.COMMAND_SEND_FAILED);
                command.setLastSendTime(System.currentTimeMillis());
            }
        }
        // 需要保存的或者发送失败的进行保存；在收到心跳后如果时间为空，则表示第一次通道不存在，重发次数为1
        if (status != Constants.COMMAND_NO_SAVE || !flag) {
            deviceLog.setCache(1);
            // cmd-commandNumber 去做redis  hash的key处理，降低重复性，因为一条指令同一秒不会有两次
            if (command.getCmd().equals(Constants.SINGLE_WHITELIST_NUMBER) || command.getCmd().equals(Constants.SET_NO_DISTURB_TIME) || command.getCmd().equals(Constants.ALARM_CLOCK)) {
                // 针对特殊的白名单和课堂模式以及设置闹钟，多存一个sequence
                InjectService.saveCommand(command.getImei(), command.getCmd().concat("-").concat(command.getCommandNumber()).concat("-").concat(String.valueOf(command.getSequence())), command);
            } else if (command.getCmd().equals(Constants.APP_DISABLE)) {
                String content = command.getContent();
                String[] split = content.split(",");
                String packageName=split[4];
                InjectService.saveCommand(command.getImei(), command.getCmd().concat("-").concat(packageName).concat("-").concat(command.getCommandNumber()), command);
            } else {
                InjectService.saveCommand(command.getImei(), command.getCmd().concat("-").concat(command.getCommandNumber()), command);
            }
        }
        deviceLog.setImei(imei);
        deviceLog.setType(command.getCmd());
        //切割指令类容,头尾去掉通用部分(并且截取掉最后一个字符)
        String s = StringUtils.substringAfter(command.getContent(), command.getCommandNumber());
        String content = s.substring(0, s.length() - 1);
        deviceLog.setCmd(content);
        deviceLog.setCommandNumber(command.getCommandNumber());
        deviceLog.setSendTime(System.currentTimeMillis());
        deviceLog.setState(flag ? 1 : 2);
        WebRemoteService webRemoteService = InjectFeignService.getWebRemoteService();
        webRemoteService.addDeviceLog(deviceLog);
        return flag;
    }

    public static void main(String[] args) {
        String s = StringUtils.substringAfter("*WT,868976030203477,SOSFUN,163550,1#", "163550");
        String content = s.substring(0, s.length() - 1);
        System.out.println(content);
    }


    /**
     * 构建设置类指令（带一个参数的那种）
     *
     * @param mqMessage
     * @return
     */
    default Command buildGeneralSetCommand(MqMessage mqMessage) {
        MqGeneralSet mqGeneralSet = (MqGeneralSet) mqMessage.getObject();
        String imei = mqGeneralSet.getImei();
        String commandNumber = mqGeneralSet.getCommandNumber();
        Object value = mqGeneralSet.getValue();
        String cmd = mqMessage.getType();
        String param = value == null ? "" : ",".concat((String) value);
        // 构建Command对象
        Command command = new Command();
        command.setImei(imei);
        command.setCommandNumber(commandNumber);
        command.setCmd(cmd);
        // 构建指令内容
        String content = "*".concat(Constants.MANUFACTURER_NAME).concat(",").concat(imei).concat(",").concat(cmd).concat(",")
                .concat(commandNumber).concat(param).concat("#");
        command.setContent(content);
        // 是否需要保存
        if (cmd.equals(Constants.SET_MONITOR_NUMBER)) {  // 监听号码不需要保存
            command.setStatus(Constants.COMMAND_NO_SAVE);
        } else {
            command.setStatus(Constants.COMMAND_NEED_SAVE);
        }
        return command;
    }

    /**
     * 构建查询类指令
     *
     * @param mqMessage
     * @return
     */
    default Command buildGeneralQueryCommand(MqMessage mqMessage) {
        MqGeneralQuery mqGeneralQuery = (MqGeneralQuery) mqMessage.getObject();
        String imei = mqGeneralQuery.getImei();
        String commandNumber = mqGeneralQuery.getCommandNumber();
        String cmd = mqMessage.getType();
        Command command = new Command();
        command.setImei(imei);
        command.setCommandNumber(commandNumber);
        command.setCmd(cmd);
        String content = "*".concat(Constants.MANUFACTURER_NAME).concat(",").concat(imei).concat(",").concat(cmd).concat(",").concat(commandNumber).concat("#");
        command.setContent(content);
        command.setLastSendTime(System.currentTimeMillis());
        command.setStatus(Constants.COMMAND_NO_SAVE);  // 查询定位需要保存，在具体处理类重新设置了
        return command;
    }

    /**
     * 构建系统设置类指令
     *
     * @param mqMessage
     * @return
     */
    default Command buildGeneralSysSetCommand(MqMessage mqMessage) {
        MqGeneralSysSet mqGeneralSysSet = (MqGeneralSysSet) mqMessage.getObject();
        String imei = mqGeneralSysSet.getImei();
        String commandNumber = mqGeneralSysSet.getCommandNumber();
        String cmd = mqMessage.getType();
        Command command = new Command();
        command.setImei(imei);
        command.setCommandNumber(commandNumber);
        command.setCmd(cmd);
        command.setLastSendTime(System.currentTimeMillis());
        String content = "*".concat(Constants.MANUFACTURER_NAME).concat(",").concat(imei).concat(",").concat(cmd).concat(",").concat(commandNumber).concat("#");
        command.setContent(content);
        command.setStatus(Constants.COMMAND_NO_SAVE);
        return command;
    }

    /**
     * 构建开关类指令
     *
     * @param mqMessage
     * @return
     */
    default Command buildGeneralSwitchCommand(MqMessage mqMessage) {
        MqGeneralSwitch generalSwitch = (MqGeneralSwitch) mqMessage.getObject();
        String imei = generalSwitch.getImei();
        String commandNumber = generalSwitch.getCommandNumber();
        String cmd = mqMessage.getType();
        String onOff = String.valueOf(generalSwitch.getOnOff());
        Command command = new Command();
        command.setImei(imei);
        command.setCommandNumber(commandNumber);
        command.setCmd(cmd);
        command.setLastSendTime(System.currentTimeMillis());
        String content = "*".concat(Constants.MANUFACTURER_NAME).concat(",").concat(imei).concat(",").concat(cmd).concat(",").
                concat(commandNumber).concat(",").concat(onOff).concat("#");
        command.setContent(content);
        command.setStatus(Constants.COMMAND_NEED_SAVE);
        return command;
    }

    /**
     * 构建回复指令
     *
     * @param mqMessage
     * @return
     */
    default Command buildReplyCommand(MqMessage mqMessage) {
        MqGeneralReply mqGeneralReply = (MqGeneralReply) mqMessage.getObject();
        String imei = mqGeneralReply.getImei();
        String commandNumber = mqGeneralReply.getCommandNumber();
        String cmd = mqMessage.getType();
        Object result = mqGeneralReply.getResult();
        String param = result == null ? "" : ",".concat((String) result);
        Command command = new Command();
        command.setImei(imei);
        command.setCommandNumber(commandNumber);
        command.setCmd(cmd);
        command.setLastSendTime(System.currentTimeMillis());
        String content = "*".concat(Constants.MANUFACTURER_NAME).concat(",").concat(imei).concat(",").concat(cmd).concat(",").
                concat(commandNumber).concat(param).concat("#");
        command.setContent(content);
        command.setStatus(Constants.COMMAND_NO_SAVE);
        return command;
    }

    default Command buildBindingStatus(DeviceBindingStatus binding) {
        String imei = binding.getImei();
        String commandNumber = binding.getCommandNumber();
        Integer status = binding.getStatus();
        String schoolName = binding.getSchoolName();
        String classesName = binding.getClassesName();
        String studentName = binding.getStudentName();
        schoolName = StringUtils.isBlank(schoolName) ? "" : UnicodeUtil.gbEncoding(schoolName);
        classesName = StringUtils.isBlank(classesName) ? "" : UnicodeUtil.gbEncoding(classesName);
        studentName = StringUtils.isBlank(studentName) ? "" : UnicodeUtil.gbEncoding(studentName);
        String content = "*WT," + imei + ",BINDINGSTATUS," + commandNumber + "," + status + ","
                + schoolName + "," + classesName + "," + studentName + "#";
        Command command = new Command();
        command.setImei(imei);
        command.setCommandNumber(commandNumber);
        command.setCmd(Constants.DEVICE_BINDING_STATUS);
        command.setContent(content);
        command.setStatus(Constants.COMMAND_NEED_SAVE);
        return command;
    }

}
